(use-modules (ice-9 textual-ports)  ; for textual reading and writing procedures
             (ice-9 binary-ports)  ; not sure if needed
             (ice-9 rdelim)  ; for `eof-object?`
             (ice-9 optargs)  ; for keyword arguments
             (srfi srfi-1)
             (json))

;; not really working well.
;; for now just make it a string and print that.
#;(define (print-json the-json)
  (define (iter json-part)
    (cond
     [(hash-table? json-part)
      (let ([alistified (hash-map->list cons json-part)])
        (map (λ (assoc)
               (cons (car assoc) (iter (cdr assoc))))
             alistified))]
     [else (list json-part)]))
(display (simple-format #f "~a\n" (iter the-json))))

(define* (print-json the-json)
  (display
   (simple-format #f "~a\n" (scm->json-string the-json #:escape #f #:pretty #t))))


(define* (get-string-from-file file-path #:key (encoding "UTF-8"))
  (call-with-input-file file-path
    (λ (port)
      (set-port-encoding! port encoding)
      (get-string-all port))))


(define* (put-string-to-file file-path string #:key (encoding "UTF-8") (mode 'replace))
  (call-with-output-file file-path
    (λ (port)
      (set-port-encoding! port encoding)
      (put-string port
                  (cond [(eq? mode 'append)
                         (string-append (get-string-from-file
                                         file-path
                                         #:encoding encoding)
                                        "\n"
                                        string)]
                        [(equal? mode 'replace) string]
                        [else string])))))


(define* (get-json-from-file file-path)
  (json-string->scm (get-string-from-file file-path)))


(define* (put-json-to-file file-path the-json
                           #:key
                           (escape-slashes #f)
                           (pretty #f)
                           (escape-unicode #f))
  (put-string-to-file file-path
                      (scm->json-string the-json
                                        #:escape escape-slashes
                                        #:pretty pretty
                                        ;; do not escape unicode chars
                                        #:unicode escape-unicode)))
